package com.example.app.moudle.main

import android.app.Activity
import android.os.Bundle
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.NetworkUtils
import com.blankj.utilcode.util.StringUtils
import com.blankj.utilcode.util.ToastUtils
import com.blankj.utilcode.util.Utils
import com.example.app.R
import com.example.app.base.BaseSupportActivity
import com.example.app.databinding.ActivityMainBinding
import com.example.app.global.EventLoginOut
import com.example.app.global.EventNetWorkChange
import com.example.app.global.GlobalConstant
import com.example.app.global.GlobalUserManager
import com.example.app.manager.Themis
import com.example.app.manager.TimerTaskManager
import com.example.app.moudle.login.LoginF
import com.libcommon.LiveEventManager
import com.libcommon.WeakHandler

class MainActivity : BaseSupportActivity<ActivityMainBinding>() {
    override fun getLogTag() = "MainActivity"
    override fun getViewBinding() = ActivityMainBinding.inflate(layoutInflater)

    companion object {
        private const val SKIP_TIME = 5
    }

    private var lastBackPressedTime = 0L
    private val weakHandler = WeakHandler()

    //网络变化设置回调
    private val netWorkChangeListener by lazy {
        object : NetworkUtils.OnNetworkStatusChangedListener {
            override fun onDisconnected() {
                LogUtils.eTag(getLogTag(), "onDisconnected")
                LiveEventManager.post(EventNetWorkChange(false, "NoNetWork"))
                ToastUtils.showShort("onDisconnected")
            }

            override fun onConnected(networkType: NetworkUtils.NetworkType?) {
                LogUtils.iTag(getLogTag(), "onConnected ${networkType?.name}-${networkType?.ordinal}")
                LiveEventManager.post(EventNetWorkChange(true, "${networkType?.name}-${networkType?.ordinal}"))
            }
        }
    }

    //app前后台变化回调
    private val appStatusChange by lazy {
        object : Utils.OnAppStatusChangedListener {
            override fun onForeground(activity: Activity?) {
                LogUtils.iTag(getLogTag(), "onForeground")
            }

            override fun onBackground(activity: Activity?) {
                LogUtils.iTag(getLogTag(), "onBackground")
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        GlobalConstant.initDeviceLevel(this)
        //注册APP前后台变化
        AppUtils.registerAppStatusChangedListener(appStatusChange)
        //注册网络变化
        NetworkUtils.registerNetworkStatusChangedListener(netWorkChangeListener)
        initObserver()
        //加载首页
        initContent()
        initAppRes()
    }

    override fun onDestroy() {
        ToastUtils.cancel()
        weakHandler.removeCallbacksAndMessages(null)
        NetworkUtils.unregisterNetworkStatusChangedListener(netWorkChangeListener)
        AppUtils.unregisterAppStatusChangedListener(appStatusChange)
        TimerTaskManager.cancelTimer()

        //杀死应用退出应用，没杀干净，我还在麦上，离开声网频道
        if (ActivityUtils.getActivityList().size == 1) {
        }
        super.onDestroy()
    }

    override fun onBackPressedSupport() {
        //2秒内 连续两次按返回键才退出
        val currentTime = System.currentTimeMillis()
        if (currentTime - lastBackPressedTime > 2000L) {
            lastBackPressedTime = currentTime
            ToastUtils.showShort("press more and exit ${StringUtils.getString(R.string.app_name)}")
        } else {
            super.onBackPressedSupport()
        }
    }


    private fun initObserver() {
        //退出登录
        LiveEventManager.observe(this, EventLoginOut::class.java) { doLoginOut() }

    }

    private fun bannerFilter(): Boolean {
        return !GlobalUserManager.isLogin()
                || findFragment(MainF::class.java) == null
                || !AppUtils.isAppForeground()
    }

    /**
     * 退出登录到主页
     */
    private fun doLoginOut() {
        popTo(MainF::class.java, false)
        backToLoginPage()
    }

    /**
     * 登陆成功，替换最底层页面为main页面
     */
    fun showMainPage() {
        loadRootFragment(R.id.flContainerView, MainF.newInstance())
        //启动定时任务
        TimerTaskManager.startTimer()
    }

    /**
     *  回退到登陆页面
     */
    fun backToLoginPage() {
        loadRootFragment(R.id.flContainerView, LoginF())
    }

    /**
     * 初始化APP资源
     */
    private fun initAppRes() {
        LogUtils.w(
            "机型判断：${
                when (GlobalConstant.getPhoneLevel()) {
                    Themis.DEVICE_LEVEL_LOW -> "低端机型"
                    Themis.DEVICE_LEVEL_MID -> "中端机型"
                    Themis.DEVICE_LEVEL_HIGH -> "高端机型"
                    else -> "旗舰机型"
                }
            }"
        )
    }

    /**
     * 判断加载首页
     */
    private fun initContent() {
        showMainPage()
    }
}